// typing-game.js - 打字速度游戏逻辑
const { playRightSound, playWrongSound, playClickSound } = require('../../../../utils/audioUtils.js');
const storageManager = require('../../../../manager/storageManager').getInstance();

Page({
  data: {
    currentIndex: 0,
    totalWords: 10,
    currentWord: null,
    wordsList: [],
    userInput: '',
    inputFocus: true,
    inputError: false,
    completedWords: [],
    correctCount: 0,
    wrongCount: 0,
    timeElapsed: 0,
    wpm: 0,
    gameOver: false,
    resultIcon: '',
    resultTitle: '',
    stars: 0,
    accuracy: 0,
    showToast: false,
    toastMessage: '',
    toastIcon: '',
    toastBg: '#4caf50',
    wordStartTime: 0
  },

  onLoad: function() {
    const app = getApp();
    this.wordDataManager = app.globalData.wordDataManager;
    this.magicCoinManager = app.getMagicCoinManager();
    this.timer = null;
    this.initGame();
  },

  onUnload: function() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },

  // 初始化游戏
  initGame: function() {
    const wordsDict = this.wordDataManager.getAllWords();
    const allWords = Object.values(wordsDict).filter(word => 
      word && word.english && word.chinese && word.english.length >= 3 && word.english.length <= 10
    );

    if (allWords.length < 10) {
      wx.showToast({
        title: '单词数量不足',
        icon: 'none'
      });
      return;
    }

    const wordsList = this.shuffleArray(allWords).slice(0, 10);

    this.setData({
      wordsList,
      currentIndex: 0,
      currentWord: wordsList[0],
      userInput: '',
      inputFocus: true,
      inputError: false,
      completedWords: [],
      correctCount: 0,
      wrongCount: 0,
      timeElapsed: 0,
      wpm: 0,
      gameOver: false,
      wordStartTime: Date.now()
    });

    this.startTimer();
  },

  // 开始计时
  startTimer: function() {
    this.timer = setInterval(() => {
      const timeElapsed = this.data.timeElapsed + 1;
      const wpm = this.calculateWPM();
      this.setData({ timeElapsed, wpm });
    }, 1000);
  },

  // 计算WPM (Words Per Minute)
  calculateWPM: function() {
    if (this.data.timeElapsed === 0) return 0;
    const minutes = this.data.timeElapsed / 60;
    return Math.round(this.data.correctCount / minutes) || 0;
  },

  // 输入处理
  onInput: function(e) {
    const value = e.detail.value.toLowerCase();
    this.setData({ 
      userInput: value,
      inputError: false
    });
  },

  // 检查单词
  checkWord: function() {
    // 播放点击音效
    playClickSound();
    
    const userInput = this.data.userInput.trim().toLowerCase();
    const correctWord = this.data.currentWord.english.toLowerCase();

    if (!userInput) {
      return;
    }

    const wordTime = ((Date.now() - this.data.wordStartTime) / 1000).toFixed(1);
    const isCorrect = userInput === correctWord;

    if (isCorrect) {
      this.handleCorrectWord(wordTime);
    } else {
      this.handleWrongWord();
    }
  },

  // 处理正确输入
  handleCorrectWord: function(wordTime) {
    const completedWords = [...this.data.completedWords, {
      ...this.data.currentWord,
      time: wordTime,
      isCorrect: true,
      animation: null
    }];

    const correctCount = this.data.correctCount + 1;

    this.setData({
      completedWords,
      correctCount,
      userInput: '',
      inputError: false
    });

    playRightSound();
    wx.vibrateShort({ type: 'light' });
    this.showToast('✓', '正确！', '#4caf50');

    setTimeout(() => {
      this.nextWord();
    }, 500);
  },

  // 处理错误输入
  handleWrongWord: function() {
    const wrongCount = this.data.wrongCount + 1;

    this.setData({
      wrongCount,
      inputError: true
    });

    playWrongSound();
    wx.vibrateShort({ type: 'heavy' });
    this.showToast('✗', '输入错误，请重试', '#f44336');

    setTimeout(() => {
      this.setData({ 
        userInput: '',
        inputError: false 
      });
    }, 1000);
  },

  // 下一个单词
  nextWord: function() {
    const nextIndex = this.data.currentIndex + 1;

    if (nextIndex >= this.data.totalWords) {
      this.endGame();
      return;
    }

    this.setData({
      currentIndex: nextIndex,
      currentWord: this.data.wordsList[nextIndex],
      wordStartTime: Date.now(),
      inputFocus: true
    });
  },

  // 格式化时间
  formatTime: function(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    // 使用兼容方式实现两位数格式
    const formattedMins = mins < 10 ? '0' + mins : mins.toString();
    const formattedSecs = secs < 10 ? '0' + secs : secs.toString();
    return formattedMins + ':' + formattedSecs;
  },

  // 打乱数组
  shuffleArray: function(array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  },

  // 显示提示信息
  showToast: function(icon, message, bg) {
    this.setData({
      showToast: true,
      toastIcon: icon,
      toastMessage: message,
      toastBg: bg
    });

    setTimeout(() => {
      this.setData({ showToast: false });
    }, 1000);
  },

  // 结束游戏
  endGame: function() {
    if (this.timer) {
      clearInterval(this.timer);
    }

    const totalAttempts = this.data.correctCount + this.data.wrongCount;
    const accuracy = totalAttempts > 0 ? Math.round((this.data.correctCount / totalAttempts) * 100) : 0;
    const wpm = this.calculateWPM();
    
    let stars = 0;
    let resultIcon = '';
    let resultTitle = '';

    if (wpm >= 30 && accuracy >= 90) {
      stars = 3;
      resultIcon = '🏆';
      resultTitle = '打字高手！';
    } else if (wpm >= 20 && accuracy >= 70) {
      stars = 2;
      resultIcon = '🌟';
      resultTitle = '表现不错！';
    } else {
      stars = 1;
      resultIcon = '👍';
      resultTitle = '继续练习！';
    }

    // 奖励魔法币
    const coins = stars * 10;
    this.magicCoinManager.addMagicCoins(coins, `打字速度游戏 - ${stars}星`);

    // 保存游戏记录
    this.saveGameRecord(stars, wpm);

    this.setData({
      gameOver: true,
      accuracy,
      wpm,
      stars,
      resultIcon,
      resultTitle
    });
  },

  // 保存游戏记录
  saveGameRecord: function(stars, wpm) {
    try {
      const gameStats = storageManager.getStorage(storageManager.STORAGE_KEYS.WORD_GAME_STATS) || {
        totalGamesPlayed: 0,
        totalStars: 0,
        highScore: 0,
        matching: { played: 0, bestScore: 0 },
        scramble: { played: 0, bestScore: 0 },
        memory: { played: 0, bestScore: 0 },
        chain: { played: 0, bestScore: 0 },
        typing: { played: 0, bestScore: 0 },
        puzzle: { played: 0, bestScore: 0 }
      };

      gameStats.totalGamesPlayed += 1;
      gameStats.totalStars += stars;
      gameStats.highScore = Math.max(gameStats.highScore, wpm);
      gameStats.typing.played += 1;
      gameStats.typing.bestScore = Math.max(gameStats.typing.bestScore, wpm);

      storageManager.setStorage(storageManager.STORAGE_KEYS.WORD_GAME_STATS, gameStats);

      const recentGames = storageManager.getStorage(storageManager.STORAGE_KEYS.RECENT_WORD_GAMES) || [];
      recentGames.unshift({
        id: Date.now(),
        gameName: '打字速度',
        icon: '⌨️',
        score: wpm,
        stars,
        timestamp: new Date().toISOString()
      });

      storageManager.setStorage(storageManager.STORAGE_KEYS.RECENT_WORD_GAMES, recentGames.slice(0, 10));
    } catch (error) {
      console.error('保存游戏记录失败:', error);
    }
  },

  // 重新开始游戏
  restartGame: function() {
    // 播放点击音效
    playClickSound();
    this.initGame();
  },

  // 返回
  goBack: function() {
    // 播放点击音效
    playClickSound();
    
    if (this.timer) {
      clearInterval(this.timer);
    }
    wx.navigateBack();
  },
  
  // 转发给朋友
  onShareAppMessage: function() {
    return {
      title: `我在打字速度游戏中达到了每分钟${this.data.wpm}个单词！快来挑战吧！`,
      path: '/pages/challenge/word-games/typing-game/typing-game',
      // imageUrl: '/images/challenge.png'
    };
  },
  
  // 分享到朋友圈
  onShareTimeline: function() {
    return {
      title: `我在打字速度游戏中达到了每分钟${this.data.wpm}个单词！快来挑战吧！`,
      query: 'from=timeline',
      // imageUrl: '/images/challenge.png'
    };
  }
});
